package org.example.user.projects.web.controller;

import org.apache.commons.lang.StringUtils;
import org.example.annotation.RequestBody;
import org.example.annotation.ResponseBody;
import org.example.user.context.ComponentContext;
import org.example.user.projects.domain.User;
import org.example.user.projects.service.UserService;
import org.example.user.projects.web.dto.BaseDTO;

import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Path;

/**
 * 登录处理器
 *
 * @author hrz
 * @since 2021/3/3 0003
 */
public class LoginController {

    private UserService userService;

    public LoginController() throws NamingException {
        // 通过组件上下文获取组件
        this.userService = ComponentContext.getInstance().lookComponent("bean/UserService");
    }

    @Path("/login")
    public String login(String email, String password, HttpServletRequest request) throws Throwable {
        if (StringUtils.isEmpty(email)) {
            request.setAttribute("errorMsg", "email can not be empty");
            return "login.jsp";
        }
        if (StringUtils.isEmpty(password)) {
            request.setAttribute("errorMsg", "password can not be empty");
            return "login.jsp";
        }
        User user = userService.findByEmail(email, password);
        if (user != null) {
            request.setAttribute("user", user);
            return "index.jsp";
        } else {
            request.setAttribute("errorMsg", "账号或密码错误");
            return "login.jsp";
        }
    }


    @Path("/register")
    @ResponseBody
    public BaseDTO register(@RequestBody User user) {
        try {
            System.out.println("==== register接收的参数：" + (user != null ? user.toString() : null));
            if (StringUtils.isEmpty(user.getEmail())) {
                return new BaseDTO(false, null, "email can not be empty");
            }
            if (StringUtils.isEmpty(user.getPassword())) {
                return new BaseDTO(false, null, "password can not be empty");
            }
            return new BaseDTO(userService.register(user), null, null);
        } catch (Throwable t) {
            t.printStackTrace();
            return new BaseDTO(false, null, "系统开小差");
        }
    }

}